import { DownOutlined, LogoutOutlined, SettingOutlined } from "@ant-design/icons";
import { Avatar, Dropdown, Menu, Modal, Skeleton, Typography } from "antd";
import classNames from "classnames";
import { get } from "lodash";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import About from "../about";
import { GlobalState } from "../globalState";
import style from "./index.module.less";
import { getLoggedInUser, ruoyiLogout } from "src/utils/ruoyi/login";

const { Title, Paragraph, Text, Link } = Typography;

const config = (window as any).__config;

const UserInfo: React.FC = () => {
  const [globalState, ] = GlobalState.useContainer();
  const [shouldAboutShow, setShouldAboutShow] = useState<boolean>(false);
  const [userInfo, setUserInfo] = useState<any>();

  useEffect(() => {
    (async () => {
      globalState.isLoggedIn && setUserInfo(await getLoggedInUser());
    })()
  }, [globalState.isLoggedIn]);

  // 展示关于信息
  const onShowAbout = useCallback(() => {
    setShouldAboutShow(true);
  }, []);

  // 下拉菜单组件
  const infoMenus = useMemo(
    () => (
      <Menu style={{ padding: "8px" }}>
        {config.links.map((item: any) => (
          <Menu.Item icon={<SettingOutlined />} style={{ padding: "8px 16px", color: "#1890ff" }}>
            <Link href={item.path} style={{ color: "#1890ff" }}>{item.name}</Link>
          </Menu.Item>
        ))}
        <Menu.Item icon={<SettingOutlined />} style={{ padding: "8px 16px", color: "#1890ff" }}>
          <Link href="/settings" style={{ color: "#1890ff" }}>系统管理</Link>
        </Menu.Item>
        <Menu.Divider />
        <Menu.Item icon={<LogoutOutlined />} style={{ padding: "8px 16px", color: "#1890ff" }}>
          <Link onClick={ruoyiLogout} style={{ color: "#1890ff" }}>退出登录</Link>
        </Menu.Item>
      </Menu>
    ),
    []
  );

  return (
    <>
      {!userInfo ? (
        <div className={style.userInfoSkeleton}>
          <Skeleton.Avatar active />
          <Skeleton.Button style={{ width: 150 }} active />
        </div>
      ) : (
        <Dropdown overlay={infoMenus}>
          <div
            className={classNames(style.username, {
              [style.__dark]:
                globalState.theme === "dark" &&
                globalState.layoutMod !== "LEFT_RIGHT",  // 左右模式用户名样式没有变动
              [style.__light]: globalState.theme === "light",
            })} style={{ whiteSpace: "nowrap" }}
          >
            <Avatar
              alt={get(userInfo, "name")}
              size="small"
              className="mr-16"
            />
            欢迎您，{get(userInfo, "name")}
            <DownOutlined style={{ marginLeft: 8 }} />
          </div>
        </Dropdown>
      )}
      <Modal
        width={450}
        visible={shouldAboutShow}
        onCancel={() => setShouldAboutShow(false)}
        footer={null}
      >
        <About />
      </Modal>
    </>
  );
};

export default UserInfo;
